package com.landiao.ctrler;

import java.io.File;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.landiao.common.Constant;
import com.landiao.common.pojo.ClientUserInfo;
import com.landiao.common.utils.CommUtil;

/**
 * 基础control
 * 
 */
public abstract class BaseCtrler {
	
	protected final Logger log = LoggerFactory.getLogger(getClass());
	
	protected static ExecutorService DOWN_FILE_EXECUTOR_SERVICE = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2);
	
	@Value("${weixin.site}")
	protected String webSite;
    
    private String viewPrefix;
    
    protected BaseCtrler() {
        setViewPrefix(defaultViewPrefix());
    }
    
    /**
     * 当前模块 视图的前缀
     * 默认
     * 1、获取当前类头上的@RequestMapping中的value作为前缀
     * 2、如果没有就使用当前模型小写的简单类名
     */
    public void setViewPrefix(String viewPrefix) {
        if (viewPrefix.startsWith("/")) {
            viewPrefix = viewPrefix.substring(1);
        }
        this.viewPrefix = viewPrefix;
    }
    
    public String getViewPrefix() {
        return viewPrefix;
    }
    
    protected String defaultViewPrefix() {
        String currentViewPrefix = "";
        RequestMapping requestMapping = AnnotationUtils.findAnnotation(getClass(), RequestMapping.class);
        if (requestMapping != null && requestMapping.value().length > 0) {
            currentViewPrefix = requestMapping.value()[0];
        }
        return currentViewPrefix;
    }
    
    /**
     * 获取视图名称：即prefixViewName + "/" + suffixName
     *
     * @return
     */
    public String viewName(String suffixName) {
        if (!suffixName.startsWith("/")) {
            suffixName = "/" + suffixName;
        }
        return getViewPrefix() + suffixName;
    }

    /**
     * @param backURL null 将重定向到默认getViewPrefix()
     * @return
     */
    protected String redirectToUrl(String backURL) {
        if (StringUtils.isEmpty(backURL)) {
            backURL = getViewPrefix();
        }
        if (!backURL.startsWith("/") && !backURL.startsWith("http")) {
            backURL = "/" + backURL;
        }
        return "redirect:" + backURL;
    }
    
    public ClientUserInfo getClientUser() { 
    	HttpSession session = this.getSession();
    	return (ClientUserInfo)session.getAttribute(Constant.SESSION_USER);
    }
    
    public HttpSession getSession() { 
    	HttpSession session = getRequest().getSession(); 
    	return session;
    } 

    public HttpServletRequest getRequest() { 
    	ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder 
    			.getRequestAttributes(); 
    	return attrs.getRequest(); 
    } 
    /**
     * 通过图片图片修改时判断图片是否有修改（通过temp和file判断）
     * @param url 例如：http://192.168.3.222:8080/xxx/xxx/a.jpeg
     * @return
     */
    public boolean isEditUrl(String url){
    	boolean reuslt =true;
		String[] data = url.split("/");
		String filepage = data[data.length-2];
		if(filepage.equals("file")){
			reuslt = false;
		}
		System.out.println(reuslt);
		return reuslt;
    }
    /**
     * 通过图片路径获取图片对应系统的真实路径
     * @param url 例如：http://192.168.3.222:8080/xxx/xxx/a.jpeg
     * @return
     */
    public String getRealUrl(String url){
    	String reuslt =null;
		if(url==null){
			return null;
		}
		String[] data = url.split("/");
		String filename = data[data.length-1];
		String filepage = data[data.length-2];
		reuslt =getSession().getServletContext().getRealPath("/")+filepage+"/"+filename;
		System.out.println(reuslt);
		return reuslt;
    }
	/**
	 * 将照片从temp中copy到file中
	 * @param url
	 * @return
	 */
	public String getphoto(String url){
		String reuslt =null;
		if(url==null){
			return null;
		}
		String[] data = url.split("/");
		String filename = data[data.length-1];
		if(!data[data.length-2].equals("file")){
			reuslt = getRequest().getScheme()+ "://"+getRequest().getServerName()+ ":" +
					 getRequest().getServerPort()+ getRequest().getContextPath() + "/file/"+filename;
			//reuslt = "http://localhost:8080/landiao/file/"+filename;
			String outUrl =getSession().getServletContext().getRealPath("/")+"file/"+filename;
			String fromUrl = getSession().getServletContext().getRealPath("/")+"temp/"+filename;
			try{	
				File oldFile = new File(outUrl);
				oldFile.delete();//删除原来的文件
				
				//文件复制封装成方法
				CommUtil.copy(new File(fromUrl), new File(outUrl));

			} catch (Exception exception) {
				exception.printStackTrace();
			} 
		}else{
			return url;
		}
		return reuslt;
	}
	/**
	 * 将照片从file中删除
	 * @param url
	 */
	public void delphoto(String url){
		String[] data = url.split("/");
		String filename = data[data.length-1];
		if(data[data.length-2].equals("file")){
			//"http://localhost:8080/landiao/file/"+filename;
			String outUrl =getSession().getServletContext().getRealPath("/")+"file/"+filename;
			try{	
				File file = new File(outUrl);
				file.delete();//删除原来的文件
			} catch (Exception exception) {
				exception.printStackTrace();
			} 
		}
	}
}
